import React, { useState, useEffect } from "react";
// import "./css.css";
export default function Khindex() {
  let [allprice, setallprice] = useState(0);
  const [check, setCheck] = useState(false); //默认全选框
  let [list, setList] = useState([
    {
      id: 1,
      name: "商品11111",
      price: 132,
      flag: true,
      img: "https://nimg.ws.126.net/?url=https://dingyue.ws.126.net/2021/0702/4ee8f496j00qvleyx0032c000hs012hc.jpg&thumbnail=650x2147483647&quality=80&type=jpg",
      num: 1,
    },
    {
      id: 2,
      name: "商品22222",
      price: 15555,
      flag: true,
      img: "https://inews.gtimg.com/newsapp_bt/0/13510081048/1000",
      num: 4,
    },
    {
      id: 3,
      name: "商品333333",
      price: 444,
      flag: false,
      img: "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F1128%2F14f91799j00r39wzt0029c000g000zkc.jpg&thumbnail=660x2147483647&quality=80&type=jpg",
      num: 1,
    },
  ]);

  useEffect(() => {
    let prices = 0;
    list.forEach((item) => {
      if (item.flag) {
        prices += item.num * item.price;
      }
    });
    setallprice(prices);

    //全选
    let res = list.some((item) => {
      if (!item.flag) {
        return true;
      }
    });
    if (res) {
      setCheck(false);
    } else {
      setCheck(true);
    }
  }, [list]);
  const change = (data) => {
    let newlist = [...list];
    let index = newlist.indexOf(data);
    newlist[index].flag = !newlist[index].flag;
    setList(newlist);
  };
  const unadd = (index, type) => {
    let newlist = [...list];
    if (list[index].num > 1 && type === "unadd") {
      newlist[index].num--;
      setList(newlist);
    } else if (type === "add") {
      newlist[index].num++;
      setList(newlist);
    }
  };
  const allchange = (check) => {
    setCheck(!check);
    const newList = list.map((item) => {
      return { ...item, flag: !check };
    });
    setList(newList)
  };
  
  return (
    <div>
      <ul>
        {list.map((item, index) => {
          return (
            <li key={index}>
              <input
                type="checkbox"
                checked={item.flag}
                onChange={() => change(item)}
              />
              <img src={item.img} alt="" width="100px" height="200px" />
              <span>
                <p>{item.name}</p>
                <p>${item.price}</p>
              </span>
              <span>
                <button onClick={() => unadd(index, "unadd")}>-</button>
                {item.num}{" "}
                <button onClick={() => unadd(index, "add")}>+</button>
              </span>
            </li>
          );
        })}
      </ul>
      <div className="foot">
        <span>
          全选{" "}
          <input
            type="checkbox"
            checked={check}
            onChange={() => allchange(check)}
          />
        </span>
        <span>总价:{allprice}</span>
      </div>
    </div>
  );
}
